import React, { useEffect, useState } from 'react';

const OrderManagement: React.FC = () => {
    const [orders, setOrders] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    useEffect(() => {
        const fetchOrders = async () => {
            try {
                const response = await fetch('/api/orders');
                if (!response.ok) {
                    throw new Error('Failed to fetch orders');
                }
                const data = await response.json();
                setOrders(data);
            } catch (err) {
                setError(err.message);
            } finally {
                setLoading(false);
            }
        };

        fetchOrders();
    }, []);

    const renderOrders = () => {
        if (loading) {
            return <p>Loading orders...</p>;
        }

        if (error) {
            return <p>Error: {error}</p>;
        }

        return (
            <ul>
                {orders.map(order => (
                    <li key={order.id}>
                        <h3>Order ID: {order.id}</h3>
                        <p>Status: {order.status}</p>
                        <p>Total: ${order.total}</p>
                        <p>Date: {new Date(order.date).toLocaleDateString()}</p>
                    </li>
                ))}
            </ul>
        );
    };

    return (
        <div>
            <h1>Order Management</h1>
            {renderOrders()}
        </div>
    );
};

export default OrderManagement;